package br.com.planningrun.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.planningrun.util.Util;

public class UploadServlet extends HttpServlet {

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String login = request.getParameter("login");
		if (login == null) {
			throw new ServletException("Login nulo");
		}
		String conteudo = request.getParameter("conteudo");
		if (conteudo == null) {
			throw new ServletException("Conteudo nulo");
		}

		String diretorio = Util.dirArquivos();

		File arquivo = new File(diretorio + "/arquivo_" + login + ".txt");

		if (arquivo.exists()) {
			arquivo.delete();
		}
		
		try{
			// if file doesn't exists, then create it
			if (!arquivo.exists()) {
				arquivo.createNewFile();
			}

			FileOutputStream fop = new FileOutputStream(arquivo); 
 
 
			fop.write(conteudo.getBytes());
			fop.flush();
			fop.close();
 
			System.out.println("Done");
 
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		response.sendRedirect("upload.html");
	}
}
